﻿using DotNetCommon.Extensions;
using System;
using System.Collections.Generic;
using System.Data;
using System.Text;

namespace DBUtil
{
    /// <summary>
    /// DBUtil中使用的object扩展方法
    /// </summary>
    public static class ObjectExtensions
    {
        /// <summary>
        /// 将对象转换为参数化数组
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="db"></param>
        /// <returns></returns>
        public static IDataParameter[] ToParameters(this object obj, DBAccess db) => obj.ToDictionary().ToParameters(db);
    }

    /// <summary>
    /// DBUtil中使用的Dictionary扩展方法
    /// </summary>
    public static class DictionaryExtensions
    {
        /// <summary>
        /// 将对象转换为参数化数组
        /// </summary>
        /// <param name="dic">字典</param>
        /// <param name="db">数据库访问对象</param>
        /// <returns></returns>
        public static IDataParameter[] ToParameters<T>(this Dictionary<string, T> dic, DBAccess db)
        {
            if (dic == null || dic.Count == 0) return new IDataParameter[0];
            var paras = new List<IDataParameter>();
            foreach (var item in dic)
            {
                paras.Add(db.CreatePara(item.Key, item.Value));
            }
            return paras.ToArray();
        }
    }
}
